package com.java.Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/cookie-session")
public class CookieSession extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // getCookies：获取所有的Cookie，为null则表示第一次访问
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie);
        }

        // addCookie：若name重复则为更新否则为新建
        Cookie cookie = new Cookie("user", new Long(Math.round(Math.random() * 4)).toString());
        cookie.setMaxAge(24 * 60 * 60); // 设置有效期
        resp.addCookie(cookie);

        // getSession：获取Session
        HttpSession session = req.getSession();
        session.setAttribute("user", "syx"); // 新增键值对
        System.out.println(session.getId()); // 获取SessionId
        System.out.println(session.isNew()); // 判断Session是否更新
        session.invalidate(); // 注销Session
        session.setMaxInactiveInterval(1); // 设置有效期
    }
}
